var ctx;

function setCtx(ctx){
    this.ctx = ctx;
}

$(function(){
	initListener();  //添加区域监听事件
})

var isLogining = false;
function userLogin(){
    var userName = $("#userName").val();
    var pwd = $("#password").val();
    //解决ie9以下placeholder与value重复的问题
    if(userName == $("#userName").attr("placeholder")){
        userName = "";
    }
    if(pwd == $("#password").attr("placeholder")){
        pwd = "";
    }
    
    if (userName == '' || userName == undefined) {
        layer.tips('请输入用户名', '#userName', {
            tips: 3
        });
        return;
    }
    if (pwd == '' || pwd == undefined) {
        layer.tips('请输入密码!', '#password', {
            tips: 3
        });
        return;
    }
    pwd = encrypt(pwd,userName);
    var index = layer.load(1);
    $.get(ctx+"/login" + "?timestamp=" + Date.parse(new Date()),{
        uname: userName,
        pwd: pwd
    },function(data){
    	data = JSON.parse(data);
        if(data.success){
            if('' != data.msg) {
                var userId = data.obj.id;
                var url = ctx + '/registerCellHouser?userId=' + userId;
                layer.close(index);
                index = layer.open({
                    type: 2,
                    title: '注册房屋',
                    content: url,
                    skin: "register",
                    area: ['530px', '550px']
                });
            } else {
                location.href = ctx + "/main?item=1";
            }
        }else{
            layer.close(index);
            layer.msg(data.msg, {icon: 5});
        }
    })
}


function loginLoad(){ 
    $('#userName').focus();
    document.onkeydown = function(e){ 
        var ev = document.all ? window.event : e; 
        if(ev.keyCode == 13) {//监听回车键
            userLogin();
        }
    }
}

function findPwd(){
	var loginName = $("#userName").val();
	if (loginName == "" || loginName == null || loginName == undefined){
      layer.msg("请输入用户手机号！",{
          icon: 3,
          time: 1000 //2秒关闭（如果不配置，默认是3秒）
      });
	  } else {
		window.location.href=ctx+"/findPassword?loginName=" + loginName;
	  }
//    msg = "找回密码";
    
//    if (loginName == "" || loginName == null || loginName == undefined){
//        layer.msg("请输入用户名！",{
//            icon: 3,
//            time: 2000 //2秒关闭（如果不配置，默认是3秒）
//        });
//    } else {
//        $.ajax({
//            url:ctx+"/isUser",
//            type:"POST",
//            data:{loginName:loginName},
//            cache : false,
//            dataType : 'json',
//            success:function(result){
//                    if(result.success){
//                        if(result.obj == loginName){
//                            layer.msg("该用户名不存在，请重新输入！",{
//                                icon: 3,
//                                time: 2000 //2秒关闭（如果不配置，默认是3秒）
//                            });
//                        } else {
//                            url = ctx + "/findPassword?loginName=" + loginName ;
//                            index = layer.open({
//                                type: 2,
//                                //skin: 'layui-layer-lan',
//                                title: msg,
//                                fix: false,
//                                shadeClose: true,
//                                scrollbar: false,
//                                maxmin: false,
//                                edit: true,
//                                closeBtn: 1,
//                                area: ['530px', '312px'],
//                                content: url,
//                                btn: ['确定', '取消']
//                            ,yes: function(index, layero){ //或者使用btn1
//                                //按钮【按钮一】的回调
//                                var iframeWin = window[layero.find('iframe')[0]['name']]; 
//                                iframeWin.savePassword();
//                                
//                            },cancel: function(index){ //或者使用btn2
//                                //按钮【按钮二】的回调
//                            }
//                            });
//                        }
//                    } else {
//                        layer.msg(result.msg,{
//                            icon: 2,
//                            time: 2000 //2秒关闭（如果不配置，默认是3秒）
//                        });
//                    }
//                }
//        });
//    }
}

/**
 * 注册用户
 */
function register() {
	var url = ctx + '/register';
    index = layer.open({
        type: 2,
        title: '注册',
        content: url,
        skin: "register",
        area: ['530px', '550px']
    });
}

//验证联系人不为空
function checkContactor() {
	var yourName = $("#yourName").val();
	if(yourName == $("#yourName").attr("placeholder")){
		yourName = "";
	}
	if(yourName == null || yourName == ""){
		layer.tips('请填写您的姓名!', '#yourName', {
			tips: 3,
			time:1000
		});
		return false;
	} else {
		return true;
	}
}

//验证店铺描述字符不超过200
function checkDescrip() {
	var describe = $("#describe").val();
	if(describe == $("#describe").attr("placeholder")){
		describe = "";
	}
	if(describe == null || describe == ""){
		layer.tips('请填写店铺描述!', '#describe', {
			tips: 3,
			time:1000
		});
		return false;
	} else {
		return true;
	}
}

//验证联系电话不为空且格式要正确
function checkContactorPhone() {
	var yourPhone = $("#yourPhone").val();
	if(yourPhone == $("#yourPhone").attr("placeholder")){
		yourPhone = "";
	}
	if(yourPhone == null || yourPhone == ""){
		layer.tips('请填写您的联系电话!', '#yourPhone', {
			tips: 3,
			time:1000
		});
		return false;
	}else{
		var reg = /^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$|(^(13[0-9]|15[0-9]|18[5|8|9])\d{8}$)/;
		if (!reg.test(yourPhone)) {
			layer.tips('电话号码格式错误，可填固定电话或手机', '#yourPhone', {
				tips : 3
			});
			return false;
		} else {
			return true;
		}
	}
}

//验证省不能为空
function checkProvinceName(){
	var province = $("#province").val();
	if(province == null || province == ""){
		layer.tips('请选择省!', '#province', {
			tips: 3,
			time:1000
		});
		return false;
	}else{
		return true;
	}
}

//验证市名称不能为空
function checkCityName(){
	var city = $("#city").val();
	if(city == null || city == ""){
		layer.tips('请选择市!', '#city', {
			tips: 3,
			time:1000
		});
	return false;
	}else{
		return true;
	}
}

//验证区名称不能为空
function checkAreaName(){
	
	var district = $("#district").val();
	if(district == null || district == ""){
		layer.tips('请选择区!', '#district', {
			tips: 3,
			time:1000
		});
	return false;
	}else{
		return true;
	}
}

//验证小区不能为空
function checkCellInfo(){
	var infoId = $("#cellInfoId").val();
	
	if(infoId == null || infoId == ""){
		layer.tips('请选择小区!', '#cellInfoId', {
			tips: 3,
		    time:1000
		});
		return false;
	}
	return true;
}

//验证店铺不能为空
function checkShop(){
	var shop = $("#shop").val();
	if(shop == null || shop == ""){
		layer.tips('请选择店铺类型!', '#shop', {
			tips: 3,
			time:1000
		});
	return false;
	}else{
		return true;
	}
}

//省市区级联
function initListener() {
	$("#province").change(function () {
		province = $('#province').val();
		if (province != '') {
			$.ajax({
		        type : "GET",
		        url : ctx + "/district/getDistrictInfoByParentId",
		        cache : false,
		        dataType : 'json',
		        data : {
		        	parentId : province
		        },
		        success : function(data) {
		        	if (data.success) {
		                var result = "<option value='" + "'>--城市--</option>";
		                $.each(data.obj, function(index, item) {
		                    result += "<option id='" + item.regionName + "'" + " value='" + item.id + "'>" + item.regionName + "</option>";
		                });
		                $("#city").html('');
		                $("#city").append(result);
		                $("#city").change();
		            }
		        }
			});
		} else {
			var result = "<option value='" + "'>--城市--</option>";
			$("#city").html('');
            $("#city").append(result);
            $("#city").change();
		}
    });
	
    $("#city").change(function () {
    	city = $('#city').val();
    	if (city != ''){
    		$.ajax({
		        type : "GET",
		        url : ctx + "/district/getDistrictInfoByParentId",
		        cache : false,
		        dataType : 'json',
		        data : {
		        	parentId : city
		        },
		        success : function(data) {
		        	if (data.success) {
		        		var result = "<option value='" + "'>--区--</option>";
		                $.each(data.obj, function(index, item) {
		                    result += "<option id='" + item.regionName + "'" + " value='" + item.id + "'>" + item.regionName + "</option>";
		                });
		                $("#district").html('');
		                $("#district").append(result);
		                $("#district").change();
		            }
		        }
			});
    	} else {
    		var result = "<option value='" + "'>--区--</option>";
			$("#district").html('');
            $("#district").append(result);
            $("#district").change();
    	}
    });
	
    $("#district").change(function () {
    	area = $('#district').val();
    	if (area != ''){
    		$.ajax({
		        type : "GET",
		        url : ctx + "/ownerHouse/getCellListByAreaId",
		        cache : false,
		        dataType : 'json',
		        data : {
		        	areaId : area
		        },
		        success : function(data) {
		        	if (data.success) {
		        		var result = "<option value='" + "'>--小区--</option>";
		                $.each(data.obj, function(index, item) {
		                    result += "<option id='" + item.cellName + "'" + " value='" + item.id + "'>" + item.cellName + "</option>";
		                });
		                $("#cellInfoId").html('');
		                $("#cellInfoId").append(result);
		                $("#cellInfoId").change();
		            }
		        }
			});
    	} else {
    		var result = "<option value='" + "'>--小区--</option>";
			$("#cellInfoId").html('');
            $("#cellInfoId").append(result);
            $("#cellInfoId").change();
    	}
    });
}

//保存我要开店信息
var shopId;
var index = parent.layer.getFrameIndex(window.name); // 先得到当前iframe层的索引
function nextStep() {
	var yourName = $("#yourName").val();
	var yourPhone = $("#yourPhone").val();
	var province = $("#province").val();
	var city = $("#city").val();
	var district = $("#district").val();
	var shop = $("#shop").val();
	var describe = $("#describe").val();
	var cellId = $("#cellInfoId").val();
	
	if (checkContactor() && checkContactorPhone() && checkProvinceName() && checkCityName() 
			&& checkAreaName() && checkShop() && checkCellInfo()) {
		
		parent.window.location.href= ctx + "/gotoOpenShop?yourName=" + yourName 
		+ "&yourPhone=" +yourPhone +  "&province=" + province + "&city=" + city + "&district=" 
		+ district +"&cellId=" + cellId + "&shop=" + shop + "&describe=" + describe;
		/*$.ajax({
			type : "POST",
			url : ctx + "/nextStep",
			cache : false,
			dataType : 'json',
			data: {
				yourName : yourName,
				yourPhone : yourPhone,
				province : province,
				city : city,
				area : district,
				shop : shop,
				describe : describe,
				cellId:cellId
			},
			success : function(result) {
				if (result.success) {
					layer.msg("操作成功",{
						icon: 1,
						time: 1000 //1秒关闭（如果不配置，默认是3秒）
					},function(){
						shopInfo = result.obj;
						parent.window.location.href= ctx + "/gotoOpenShop?shopInfo=" + shopInfo;
					});
				} else {
					layer.msg("操作失败",{
						icon: 2,
						time: 1000
					});
				}
			}
		});*/
	}
}
